package com.parking.status.sync.netty.util;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringWriter;

/*
 * Jackson Json Object Mapper
 * */
public class PojoMapper {

    private static JsonFactory factory = new JsonFactory();
    private static ObjectMapper oMapper = new ObjectMapper();// 映射对象

    public static ObjectMapper getObjectMapper() {
        return oMapper;
    }

    // Json to Object
    public static <T> T fromJson(String jsonAsString, Class<T> pojoClass) {
        try {
            return oMapper.readValue(jsonAsString, pojoClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Json to Object
    public static <T> T fromJson(String jsonAsString,
                                 TypeReference<T> valueTypeRef) {
        try {
            return oMapper.readValue(jsonAsString, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Json to Object
    public static <T> T fromJson(FileReader fr, Class<T> pojoClass) {
        try {
            return oMapper.readValue(fr, pojoClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Object to Json
    public static String toJson(Object pojo) {
        String result = null;
        try {
            result = toJson(pojo, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // Object to Json
    public static String toJson(Object pojo, boolean prettyPrint) {
        try {
            StringWriter sw = new StringWriter();
            JsonGenerator jg = factory.createGenerator(sw);
            if (prettyPrint) {
                jg.useDefaultPrettyPrinter();
            }
            oMapper.writeValue(jg, pojo);
            return sw.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // Object to Json
    public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint) {
        try {
            JsonGenerator jg = factory.createGenerator(fw);
            if (prettyPrint) {
                jg.useDefaultPrettyPrinter();
            }
            oMapper.writeValue(jg, pojo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
